<template>
  <el-tabs v-model="activeTab">
    <el-tab-pane label="小区管理" name="area">
      <div>
        <el-button type="primary" @click="openDialog()">新增小区</el-button>
        <el-table :data="tableData" style="width: 100%; margin-top: 16px">
          <el-table-column type="index" :index="(index) => index + 1" label="编号" width="80" />
          <el-table-column prop="amName" label="管理员" width="100" />
          <el-table-column prop="aname" label="小区名称" />
          <el-table-column prop="abuildYear" label="建成年份" />
          <el-table-column prop="aaddress" label="小区地址" />
          <el-table-column prop="adesc" label="小区描述" />
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button size="small" @click="openDialog(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin-top: 16px"
          background
          layout="prev, pager, next, jumper, ->, total"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
      <el-dialog :title="dialogTitle" v-model="dialogVisible">
        <el-form :model="form" label-width="90px">
          <el-form-item label="管理员ID">
            <el-select v-model="form.amId" placeholder="请选择管理员" @change="handleManagerChange">
              <el-option v-for="manager in areaManagers" :key="manager.id" :label="manager.amName" :value="manager.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="小区名称" required>
            <el-input v-model="form.aname" />
          </el-form-item>
          <el-form-item label="建成年份">
          <el-date-picker
            v-model="form.abuildYear"
            type="year"
            format="YYYY"
            value-format="YYYY"
            placeholder="选择年份"
          />
        </el-form-item>
          <el-form-item label="小区地址">
            <el-input v-model="form.aaddress" />
          </el-form-item>
          <el-form-item label="小区描述">
            <el-input v-model="form.adesc" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
      </el-dialog>
    </el-tab-pane>
    <!-- 其他Tab后续补充 -->
  </el-tabs>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessageBox } from 'element-plus';
import { postRequest, putRequest, deleteRequest ,getRequest} from '@/utils/request';

const activeTab = ref('area');
const tableData = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const dialogVisible = ref(false);
const dialogTitle = ref('新增小区');
const form = reactive({
  id: null,
  amId: '',
  amName: '',
  aname: '',
  abuildYear: '',
  aaddress: '',
  adesc: ''
});
const areaManagers = ref([]);

function fetchData() {
  postRequest('/area/getAreaByPage', { current: currentPage.value, size: pageSize.value }).then(res => {
    if (res && res.data && res.data.data) {
      tableData.value = Array.isArray(res.data.data.areas) ? res.data.data.areas : [];
      total.value = res.data.data.total || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  }).catch(error => {
    console.error('获取数据失败:', error);
    tableData.value = [];
    total.value = 0;
  });
}

function fetchAreaManagers() {
  getRequest('/areaManager/getAreaManagerList').then(res => {
    if (res && res.data) {
      console.log(res.data);
      
// `areaManagers.value` 是一个响应式的数组，数组没有 `add` 方法，应该使用 `push` 方法添加元素
res.data.data.forEach(element => {
  console.log(element.amName);
  areaManagers.value.push({
    id: element.id,
    amName: element.amName
  });
});
      
    }
  }).catch(error => {
    console.error('获取管理员列表失败:', error);
  });
}

function openDialog(row) {
  if (row) {
    dialogTitle.value = '编辑小区';
    Object.assign(form, row);
    form.amName = row.amName || '';
  } else {
    dialogTitle.value = '新增小区';
    form.id = null;
    form.amId = '';
    form.aname = '';
    form.abuildYear = '';
    form.aaddress = '';
    form.adesc = '';
  }
  dialogVisible.value = true;
}

function handleSubmit() {
  if (form.id) {
    putRequest('/area/updateAreaById', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  } else {
    postRequest('/area/addArea', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  }
}

function handleDelete(id) {
  ElMessageBox.confirm('确定要删除该记录吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRequest(`/area/deleteAreaById/${id}`).then(() => {
      fetchData();
    });
  }).catch(() => {});
}

function handlePageChange(page) {
  currentPage.value = page;
  fetchData();
}

onMounted(() => {
  fetchData();
  fetchAreaManagers();
});

function handleManagerChange(amId) {
  const selectedManager = areaManagers.value.find(manager => manager.id === amId);
  if (selectedManager) {
    form.amName = selectedManager.amName;
  } else {
    form.amName = '';
  }
}
</script>